using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;

public class PlayersManager : NetworkBehaviour
{
    public static PlayersManager instance {get;private set;}

    private Dictionary<ulong,Player> players = new ();

    private Vector3[] spawnPositions = {
        new Vector3(0, 0, 0),
        new Vector3(-1, 0, 0),
        new Vector3(-2, 0, 0),
        new Vector3(-3, 0, 0),
        new Vector3(-4, 0, 0)
    };

    private int playerCount = 0;

    private void Awake() {
        Debug.Log("playersManager awake... instance is " + instance);
        instance = this;
        if(IsServer && instance == null) {
            Debug.Log("server playersManager init over");
        }
    }

    public override void OnNetworkDespawn()
    {
        if(!IsServer) return;
        // 服务端负责管理玩家对象
        Debug.Log("server OnNetworkDespawn");
        if(instance == null) {
            instance = this;
        }
    }

    public Vector3 GetSpawnPosition()
    {
        Vector3 position = spawnPositions[playerCount % spawnPositions.Length];
        playerCount++;
        return position;
    }

    public Vector3 GetPlayersCenterPosition() {
        if(IsServer) {
            Vector3 centerPoint = Vector3.zero;
            GetAllPlayers().ForEach((Player player) => {
                if(player != null) {
                    centerPoint += player.transform.position;
                }
            });
            
            return centerPoint / (Mathf.Clamp(players.Count,1,10));
        }
        return Vector3.zero;
    }

     // 添加玩家到字典中
    public void RegisterPlayer(Player player)
    {
        players[player.OwnerClientId] = player;
    }

    // 移除玩家
    public void UnregisterPlayer(Player player)
    {
        if (players.ContainsKey(player.OwnerClientId))
        {
            players.Remove(player.OwnerClientId);
        }
    }

    // 获取所有玩家
    public List<Player> GetAllPlayers()
    {
        return new List<Player>(players.Values);
    }
}
